package com.isoft.service.impl;

import com.isoft.entity.DfmeAirlEntity;
import com.isoft.mapper.DfmeAirlMapper;
import com.isoft.service.DfmeAirlService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeAirlServiceImpl implements DfmeAirlService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeAirlServiceImpl.class);

    @Autowired
    private DfmeAirlMapper dfmeAirlMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-AIRL XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeAirlEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeAirlEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid DFME-AIRL XML structure");
            }

            processFlightData(entity);

            return "DFME-AIRL data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-AIRL XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-AIRL XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeAirlEntity entity) {
        // 1. 插入元数据
        try {
            dfmeAirlMapper.insertMeta(entity);
        } catch (Exception e) {
            logger.error("Failed to insert meta data", e);
            throw new RuntimeException("Failed to insert meta data: " + e.getMessage());
        }

        // 2. 插入航班基础信息
        try {
            dfmeAirlMapper.insertFlightBase(entity);
        } catch (Exception e) {
            logger.error("Failed to insert flight base data", e);
            throw new RuntimeException("Failed to insert flight base data: " + e.getMessage());
        }

        // 3. 处理机场和航线信息
        if (entity.getDflt().getAirl() != null && entity.getDflt().getAirl().getArpts() != null) {
            entity.getDflt().getAirl().getArpts().forEach(arpt -> {
                try {
                    // 确保机场存在
                    if (arpt.getAirportCode() != null && !arpt.getAirportCode().isEmpty()) {
                        if (dfmeAirlMapper.checkAirportExists(arpt.getAirportCode()) == 0) {
                            dfmeAirlMapper.insertAirport(
                                    arpt.getAirportCode(),
                                    arpt.getAirportTerminal());
                        }
                    }
                } catch (Exception e) {
                    logger.warn("Failed to process airport {}: {}",
                            arpt.getAirportCode(), e.getMessage());
                }
            });

            // 插入航线信息
            try {
                dfmeAirlMapper.insertFlightRoute(entity);
            } catch (Exception e) {
                logger.error("Failed to insert flight route data", e);
                throw new RuntimeException("Failed to insert flight route data: " + e.getMessage());
            }
        }

        // 4. 新增：插入航班异常信息到FLIGHT_IRREGULARITY表
        try {
            dfmeAirlMapper.insertIrregularity(entity);
        } catch (Exception e) {
            logger.error("Failed to insert irregularity data", e);
            throw new RuntimeException("Failed to insert irregularity data: " + e.getMessage());
        }
    }

    @Override
    public void parseAndSave(DfmeAirlEntity entity) {
        if (entity == null || entity.getDflt() == null) {
            throw new IllegalArgumentException("Invalid entity data");
        }
        processFlightData(entity);
    }
}